package com.minshenglife.zanzan.web.weixin.service;

import java.util.Date;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.minshenglife.zanzan.entity.AccessToken;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.service.AccessTokenService;

@Component
public class WXAccTokenService {

	Logger log = LoggerFactory.getLogger(WXAccTokenService.class);

	@Resource
	AccessTokenService accessTokenService;

	/**
	 * 获取微信token
	 * 
	 * @return
	 * @throws Exception
	 */
	public synchronized String getWXAccToken() throws Exception {
		String flag = WXKeys.WX_APPID;
		AccessToken at = accessTokenService.getWXAccessToken(flag);
		if (at == null) {
			log.debug("start new create access_token");
			String token = WXBaseService.getWXAccessToken();
			accessTokenService.insertWXAccessToken(flag, token);
			return token;
		} else {
			// 校验时间是否超过
			if (new Date().getTime() >= at.getEnd_time().getTime()) {
				log.debug("access_token 失效 ，重新 create access_token");
				// 重新录入
				String token = WXBaseService.getWXAccessToken();
				accessTokenService.insertWXAccessToken(flag, token);
				return token;
			} else {
				return at.getAccessToken();
			}
		}
	}

}
